//
//  MTMainViewController.m
//  MeToo
//
//  Created by 俊松何 on 2018/7/3.
//  Copyright © 2018年 tianxie. All rights reserved.
//

#import "MTMainViewController.h"
#import "LBTabBar.h"
#import "MTPublishActionView.h"
#import "LTProfileViewController.h"
#import "MTLiveListController.h"
#import "PlaceholderViewController.h"
#import "MTLoginFristController.h"
#import "HLiveController.h"
#import "PPGetAddressBook.h"
#import "MTLiveContainerController.h"

#import "FanqieApiHelper.h"

NSString *const LTTabBarItemTitle = @"LTTabBarItemTitle";
NSString *const LTTabBarItemImage = @"LTTabBarItemImage";
NSString *const LTTabBarItemSelectedImage = @"LTTabBarItemSelectedImage";

//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;

@interface MTMainViewController ()<LBTabBarDelegate,MTPublishActionViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITabBarControllerDelegate>

@property(nonatomic,strong) MTPublishActionView *publishActionView;

@property (nonatomic, strong)NSMutableArray *selectedPhotos;
@property (nonatomic, strong)NSMutableArray *selectedAssets;

@property (nonatomic, strong)UIImagePickerController *imagePickerVc;

@property (strong, nonatomic) NSDate *lastPlaySoundDate;

@property(nonatomic,strong) NSArray *tabBarItemsAttributes;

@end

@implementation MTMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     [self setUpAllChildVc];
    self.delegate = self;
    
    //创建自己的tabbar，然后用kvc将自己的tabbar和系统的tabBar替换下
    LBTabBar *tabbar = [[LBTabBar alloc] init];
    tabbar.myDelegate = self;
//    //kvc实质是修改了系统的_tabBar
    [self setValue:tabbar forKeyPath:@"tabBar"];
    
    [self setupUnreadMessageCount];
    
    //更新当前用户的个人信息
    [MTUserModel updateCurrentUserInfo];
    
    [[MTWalletApiManager manager] getUserWalletInfoWithcomplation:^(MTWalletInfo *walletInfo, MTError *boerror) {
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self requestAddressBookAuthorization];
    });
    
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:LoginTokenError object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        NSString *reson = x.object;
        [self loginTokenError:reson];
    }];
    [self updateApp];
}

-(void)updateApp
{
    [[LTThridKeyCfgManger manager] getVersionInfoWithCompletion:^(UpdateModel *model, MTError *error) {
        if(error == nil)
        {
            if (model.hasNewVersion)
            {
                UIAlertController *alterVc = [UIAlertController alertControllerWithTitle:NSLTLocalizedString(@"update.versionUpate", nil) message:model.message preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"update.update", ) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSURL *url = [NSURL URLWithString:model.downloadUrl];
                    [[UIApplication sharedApplication] openURL:url];
                }];
                UIAlertAction *cancleaction = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"update.noupdate", ) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                }];
                [alterVc addAction:action];
                if (!model.forceUpdate)
                {
                    [alterVc addAction:cancleaction];
                }
                [self presentViewController:alterVc animated:YES completion:nil];
            }
        }
    }];
}






-(void)requestAddressBookAuthorization
{
    
    // 1.获取授权状态
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if( CNAuthorizationStatusNotDetermined == status)
    {
        NSString *tip = @"contact.Introduction";
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:NSLTLocalizedString(@"contact.pptitle", nil) message:NSLTLocalizedString(tip, nil) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"contact.no", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"contact.yes", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 获取通讯录权限
            [PPGetAddressBook requestAddressBookAuthorization];
        }];
        [alertVc addAction:action1];
        [alertVc addAction:action2];
        [kWindow.rootViewController presentViewController:alertVc animated:YES completion:^{
            
        }];
    }
    
    
    
}

-(void)loginTokenError:(NSString *)reson
{
    [[MTUserDataManager manager] logout];
    [[LTClient sharedClient] loginOut];
    
    MTLoginFristController *fristVc = [MTLoginFristController baseStoryBordWithName:@"Login"];
    MTNavigationController *nav = [[MTNavigationController alloc] initWithRootViewController:fristVc];
    kWindow.rootViewController = nav;
    UIAlertController *alterVc = [UIAlertController alertControllerWithTitle:@"登录过期" message:@"登录已过期，请重新登录!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alterVc addAction:action1];
    [kWindow.rootViewController presentViewController:alterVc animated:YES completion:nil];
}

- (void)setUpAllChildVc
{
//    MTHomeViewController *HomeVC = [MTHomeViewController homeVc];
//    [self setUpOneChildVcWithVc:HomeVC Image:self.tabBarItemsAttributes[0][LTTabBarItemImage] selectedImage:self.tabBarItemsAttributes[0][LTTabBarItemSelectedImage] title:self.tabBarItemsAttributes[0][LTTabBarItemTitle]];
    
    MTLiveContainerController *FishVC = [MTLiveContainerController containerVc];
    [self setUpOneChildVcWithVc:FishVC Image:self.tabBarItemsAttributes[1][LTTabBarItemImage] selectedImage:self.tabBarItemsAttributes[1][LTTabBarItemSelectedImage] title:self.tabBarItemsAttributes[1][LTTabBarItemTitle]];
//    ChatMainViewController *chatVc = [ChatMainViewController chatVc];
//    [self setUpOneChildVcWithVc:chatVc Image:self.tabBarItemsAttributes[2][LTTabBarItemImage] selectedImage:self.tabBarItemsAttributes[2][LTTabBarItemSelectedImage] title:self.tabBarItemsAttributes[2][LTTabBarItemTitle]];
    LTProfileViewController *MineVC = [LTProfileViewController profileVc];
    [self setUpOneChildVcWithVc:MineVC Image:self.tabBarItemsAttributes[3][LTTabBarItemImage] selectedImage:self.tabBarItemsAttributes[3][LTTabBarItemSelectedImage] title:self.tabBarItemsAttributes[3][LTTabBarItemTitle]];
}

#pragma mark - 初始化设置tabBar上面单个按钮的方法

/**
 *  @author li bo, 16/05/10
 *
 *  设置单个tabBarButton
 *
 *  @param Vc            每一个按钮对应的控制器
 *  @param image         每一个按钮对应的普通状态下图片
 *  @param selectedImage 每一个按钮对应的选中状态下的图片
 *  @param title         每一个按钮对应的标题
 */
- (void)setUpOneChildVcWithVc:(UIViewController *)Vc Image:(NSString *)image selectedImage:(NSString *)selectedImage title:(NSString *)title
{
    MTNavigationController *nav = [[MTNavigationController alloc] initWithRootViewController:Vc];
    
    UIColor *selectColor = mainTintColor;
    UIColor *noramlColor = RGB(204, 204, 204);
    
    [Vc.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:noramlColor} forState:UIControlStateNormal];
    [Vc.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:selectColor} forState:UIControlStateSelected];
    
//    Vc.view.backgroundColor = [self randomColor];
    
    UIImage *myImage = [UIImage imageNamed:image];
    myImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    //tabBarItem，是系统提供模型，专门负责tabbar上按钮的文字以及图片展示
    Vc.tabBarItem.image = myImage;
    UIImage *mySelectedImage = [UIImage imageNamed:selectedImage];
    mySelectedImage = [mySelectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    Vc.tabBarItem.selectedImage = mySelectedImage;
    Vc.tabBarItem.title = title;
    Vc.navigationItem.title = title;
    [self addChildViewController:nav];
    
}



- (NSArray *)tabBarItemsAttributes {
    if(_tabBarItemsAttributes == nil){
        NSDictionary *dict1 = @{
                                LTTabBarItemTitle : NSLTLocalizedString(@"tabbar.home", @"tabbar.home"),
                                LTTabBarItemImage : @"tabbar_home",
                                LTTabBarItemSelectedImage : @"tabbar_homeHL",
                                };
        
        NSDictionary *dict2 = @{
                                LTTabBarItemTitle : NSLTLocalizedString(@"tabbar.live", @"live"),
                                LTTabBarItemImage : @"tabbar_Live",
                                LTTabBarItemSelectedImage : @"tabbar_LiveHL",
                                };
        
        NSDictionary *dict3 = @{
                                LTTabBarItemTitle : NSLTLocalizedString(@"tabbar.message", @"message"),
                                LTTabBarItemImage : @"tabbar_chat",
                                LTTabBarItemSelectedImage : @"tabbar_chatHL",
                                };
        
        NSDictionary *dict4 = @{
                                LTTabBarItemTitle : NSLTLocalizedString(@"tabbar.me", @"me"),
                                LTTabBarItemImage : @"tabbar_my",
                                LTTabBarItemSelectedImage : @"tabbar_myHL",
                                };
        
        _tabBarItemsAttributes = @[dict1, dict2, dict3, dict4];
    }
    return _tabBarItemsAttributes;
}


-(void)reloadLauageData
{
    _tabBarItemsAttributes = nil;
    [self.viewControllers enumerateObjectsUsingBlock:^(__kindof UINavigationController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop){
        UIViewController *vc = obj.viewControllers[0];
        vc.title = self.tabBarItemsAttributes[idx][LTTabBarItemTitle];
    }];
}


-(void)setPlaceHolderVc
{
    PlaceholderViewController *placeVc = [[PlaceholderViewController alloc] init];
    UIImage *myImage = [UIImage imageNamed:@"post_normal"];
    myImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    placeVc.tabBarItem.image = myImage;
    placeVc.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0);
    [self addChildViewController:placeVc];
    
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if([viewController isKindOfClass:NSClassFromString(@"PlaceholderViewController")])
    {
        [self.publishActionView show];
        return NO;
    }
    return YES;
}


#pragma mark - ------------------------------------------------------------------
#pragma mark - LBTabBarDelegate
//点击中间按钮的代理方法
- (void)tabBarPlusBtnClick:(LBTabBar *)tabBar
{
    [self.publishActionView show];
}

-(void)buttonClick:(NSInteger)type
{
    //直播
    if(type ==1)
    {
        //创建直播
        [[FanqieApiHelper helper] presentCreateLiveVcFromVc:self];
    }
}


#pragma mark - 选择图片
- (void)pushTZImagePickerController {
   
}

#pragma mark - 处理视频地址方法
- (void)handelVideoWithAsset:(AVAsset* )asset {
   
}




-(MTPublishActionView *)publishActionView
{
    if(_publishActionView == nil)
    {
        _publishActionView = [MTPublishActionView publishActionView];
        _publishActionView.deleagte = self;
    }
    return _publishActionView;
}
#pragma mark - 懒加载 selectedPhotos
- (NSMutableArray* )selectedPhotos {
    if (!_selectedPhotos) {
        _selectedPhotos = [NSMutableArray array];
    }
    
    return _selectedPhotos;
}

#pragma mark - 懒加载 selectedAssets
- (NSMutableArray* )selectedAssets {
    if (!_selectedAssets) {
        _selectedAssets = [NSMutableArray array];
    }
    
    return _selectedAssets;
}


//IM相关操作
-(void)setupUnreadMessageCount
{
  
}

-(void)setupUnreadApplyCount
{
    
    [self setupUnreadMessageCount];
}

- (void)playSoundAndVibration
{


}

-(void)showNotificationWithMessage:(LTMessage *)message
{
    
}

@end
